﻿using Dapper;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Mysql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HDLogCenter.Dal.Repos
{
    public class AppConfigRepo
    {
        private readonly DbService _dbService;

        public AppConfigRepo(DbService dbService)
        {
            _dbService = dbService;
        }

        public async Task<IEnumerable<AppConfigModel>> GetAllAsync()
        {
            using (var connection = _dbService.GetConnection())
            {
                return await connection.GetListAsync<AppConfigModel>();
            }
        }

        public async Task<AppConfigModel> GetByIdAsync(long id)
        {
            using (var connection = _dbService.GetConnection())
            {
                return await connection.GetAsync<AppConfigModel>(id);
            }
        }

        public async Task<AppConfigModel> GetByAppCodeAsync(string appCode)
        {
            using (var connection = _dbService.GetConnection())
            {
                var result = await connection.GetListAsync<AppConfigModel>(new { AppCode = appCode });
                return result.FirstOrDefault();
            }
        }

        public async Task<int?> CreateAsync(AppConfigModel appConfig)
        {
            using (var connection = _dbService.GetConnection())
            {
                appConfig.CreateTime = DateTime.Now;
                appConfig.UpdateTime = DateTime.Now;
                return await connection.InsertAsync(appConfig);

            }
        }

            public async Task<bool> UpdateAsync(AppConfigModel appConfig)
        {
            using (var connection = _dbService.GetConnection())
            {
                appConfig.UpdateTime = DateTime.Now;
                var result = await connection.UpdateAsync(appConfig);
                return result > 0;
            }
        }

        public async Task<bool> DeleteAsync(long id)
        {
            using (var connection = _dbService.GetConnection())
            {
                var result = await connection.DeleteAsync<AppConfigModel>(id);
                return result > 0;
            }
        }
    }
}
